package com.hzdl.car.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzdl.car.bean.Menu;
import com.hzdl.car.bean.Role;
import com.hzdl.car.mapper.MenuMapper;
import com.hzdl.car.mapper.RoleMapper;
import com.hzdl.car.service.RoleService;
import com.hzdl.car.vo.RoleVo;
import com.hzdl.car.vo.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceimpl implements RoleService {

    @Autowired
    private RoleMapper mapper;

    @Autowired
    private MenuMapper menuMapper;
    @Override
    public PageInfo<Role> findByWhere(RoleVo roleVo) {
        PageHelper.startPage(roleVo.getPage(),roleVo.getLimit());
        List<Role> list = mapper.findByWhere(roleVo);
        return new  PageInfo<>(list);
    }

    @Override
    public int updateRoleMenu(RoleVo roleVo,Integer[] ids) {

        int row=0;
         mapper.deleteRoleMenuByRoleId(roleVo.getRoleid());

            for (Integer id : ids) {
                row += mapper.add(roleVo.getRoleid(), id);
            }

        return row;
    }

    @Override
    public List<TreeNode> findAll(Integer pid, Integer roleId) {
        List<Menu> listAll=menuMapper.findAll();
        List<Menu> roleMenuList = mapper.findMenuByRid(roleId);
        List<TreeNode> list = new ArrayList<>();

        for(Menu menu1: listAll){
            String checkArr = "0";

            for(Menu menu2:roleMenuList){

                if (menu1.getId()==menu2.getId()){
                    checkArr="1";
                    break;
                }
            }
            TreeNode treeNode = new TreeNode(menu1.getId() ,menu1.getPid() ,menu1.getName() ,checkArr);
            list.add(treeNode);
        }
        List<TreeNode> lastList = new ArrayList<>();
        for (TreeNode treeNode1:list){
            if (treeNode1.getPid()==0){
                lastList.add(treeNode1);
            }
            for (TreeNode treeNode2:list){

                if(treeNode1.getId() == treeNode2.getPid()){
                    treeNode1.getChildren().add(treeNode2);
                }
            }
        }
        return lastList ;
    }

    @Override
    public int add1(RoleVo roleVo) {
        return mapper.add1(roleVo);
    }

    @Override
    public int update(RoleVo roleVo) {
        return mapper.update(roleVo);
    }

    @Override
    public int delete(Integer id) {
        return mapper.delete( id);
    }
}
